//
//  PictureCollectionViewCell.swift
//  SinaMicroblog
//
//  Created by 唐绍禹 on 15/8/11.
//  Copyright © 2015年 唐绍禹. All rights reserved.
//

import UIKit
import SDWebImage
class PictureCollectionViewCell: UICollectionViewCell {
    var imageURL: NSURL? {
        didSet{
            iconView.sd_setImageWithURL(imageURL) { (image, _, _, _) -> Void in
                
                if image == nil {
                    print("下载图像失败")
                    return
                }
                self.setupImagePosition()
            }
        }
    }
    
    private func setupImagePosition() {
        
        let s = displayImageSize(iconView.image!)
        
        if s.height < scrollView.bounds.height {
            //短图
            let y = (scrollView.bounds.height - s.height) * 0.5
            
            iconView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
            
        } else {
            //长图
            
            iconView.frame = CGRect(origin: CGPointZero, size: s)
            scrollView.contentSize = s
            
        }
    }
    
    private func displayImageSize(image:UIImage) -> CGSize {
        let scale = image.size.height / image.size.width
        let h = scale * scrollView.bounds.width
        return CGSize(width: scrollView.bounds.width, height: h)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(scrollView)
        scrollView.addSubview(iconView)
        
        //设置布局
        scrollView.frame = UIScreen.mainScreen().bounds
        
        prepareScrollView()
    }
    
    private func prepareScrollView() {
        scrollView.delegate = self
        
        scrollView.maximumZoomScale = 2
        scrollView.minimumZoomScale = 0.5
    }
    
    //懒加载控件
    private lazy var scrollView = UIScrollView()
    private lazy var iconView = UIImageView()
    
}

extension PictureCollectionViewCell: UIScrollViewDelegate {
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return iconView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        
        offsetX = offsetX < 0 ? 0 : offsetX
        offsetY = offsetY < 0 ? 0 : offsetY
        
//        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
        scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
    }
    
}
